from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
import json
from .forms import LoginForm, RegisterForm
from .tool import tools
from . import models

ai = tools.Tools()
ai.InitSettings()
us = "初始用户名"


def TestUrl(request):
    PageName = "test.html"
    page = render(request=request, template_name=PageName)
    return page


def FastUrl(request):
    return redirect('index')


#基本界面
def LoginInfo(request):
    page_name = 'login.html'
    context = {}
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(request, username=username, password=password)
            if user is not None:
                global us
                us = username
                login(request, user)
                return redirect('index')  # 替换为登录成功后的重定向 URL
            else:
                error = "您的用户名或者密码不正确"
                context['error'] = error

    page = render(request=request, template_name=page_name, context=context)
    return page


#登入页面
def RegisterInfo(request):
    page_name = 'register.html'
    context = {}
    if request.method == "POST":
        form = RegisterForm(request.POST)
        print(form)
        print('done')
        if form.is_valid():
            form.save()
            return redirect('login')
    else:
        form = RegisterForm()
    context['form'] = form
    page = render(request=request, template_name=page_name, context=context)
    return page


#注册页面
def LogoutInfo(request):
    logout(request)
    return redirect('index')


def FAQInfo(request):
    page_name = 'faq.html'
    context = {}

    page = render(request=request, template_name=page_name, context=context)
    return page


#常见问题

def ContactInfo(request):
    page_name = 'contact.html'
    context = {}

    page = render(request=request, template_name=page_name, context=context)
    return page


#联系我们

###########主页
def IndexInfo(request):
    page_name = "index.html"
    context = {}
    page = render(request=request, template_name=page_name, context=context)
    return page


##########计算工具
def UnaryFormInfo(request):
    page_name = 'UnaryCalculations.html'
    context = {}

    #下拉面板，创建省市选项
    city_item = ai.ProvinceData
    context['province'] = []
    city = {}

    for _ in city_item.keys():
        context['province'].append([_, city_item[_][0]])
        city[_] = city_item[_][1]
    if request.method == "POST":
        nid = request.POST.get('province_id', 0)
        try:
            cityLog = city[int(nid)]
            if cityLog:
                ai.SelectProvince = city_item[int(nid)][0]
                return JsonResponse({'cityLog': cityLog})
        except KeyError:
            pass
        ProvinceName = ai.SelectProvince
        s=ProvinceName
        Commit = request.POST.get('inputCommit', '...')
        TreeType = request.POST.get('inputTree', '...')
        City = request.POST.get('inputCity', '...')
        Pos = request.POST.get('Pos', '未输入')
        Quantity = int(request.POST.get('Quantity', 0))
        Diameter = int(request.POST.get('Diameter', 0))
        Height = int(request.POST.get('Height', 0))
        if '...' in [Commit, TreeType, City] or Quantity <= 0 or Diameter <= 0 or Height <= 0:
            #信息未输入完全，抛出提示
            context['error'] = []
            if TreeType == '...':
                context['error'].append("请选择树种的种类")
            if City == '...':
                context['error'].append("请选择树种所在的城市")
            if Quantity <= 0:
                context['error'].append("请输入正确树种数量")
            if Diameter <= 0:
                context['error'].append("请输入正确的树种半径")
            if Height <= 0:
                context['error'].append("请输入正确的树种高度")
        else:
            #输入完全，开始计算逻辑
            # print(Commit, TreeType, City, Pos, Quantity, Diameter, ProvinceName)
            context['Commit'] = Commit
            context['City'] = City
            context['Province'] = ProvinceName
            context['Pos'] = Pos
            if TreeType == "杨树":
                result = ai.PoplarInfo(Diameter=Diameter, Height=Height, quantity=Quantity)
                context['Item'] = result
                global us
                models.UserInfor.objects.create(
                                    ProvinceName=s,
                                    TreeSpecies='Unary_trees',
                                    Commit=Commit,
                                    TreeType=TreeType,
                                    City=City,
                                    Pos=Pos,
                                    Quantity=Quantity,
                                    Diameter=Diameter,
                                    Height=Height,
                                    dry_biomass=result['dry_biomass'],
                                    total_biomass=result['total_biomass'],
                                    total_biomass_repeated=result['total_biomass_repeated'],
                                    carbon_storage=result['carbon_storage'],
                                    total_carbon_storage_all=result['total_carbon_storage_all'],
                                    carbon_sinks=result['carbon_sinks'],
                                    total_carbon_sinks=result['total_carbon_sinks'],
                                    username=us
                )
    page = render(request=request, template_name=page_name, context=context)
    return page

def BinaryFormInfo(request):
    page_name = 'BinaryCalculations.html'
    context = {}

    page = render(request=request, template_name=page_name, context=context)
    return page

def GinkgoBilobaFormInfo(request):
    page_name = 'GinkgoBilobaCalculations.html'
    context = {}
    page = render(request=request, template_name=page_name, context=context)
    return page
##########总结工具台

def SubmitInfo(request):
    page_name = 'Submit.html'
    context = {}
    page = render(request=request, template_name=page_name, context=context)
    return page

@login_required(login_url='login')
def AuditInfo(request):
    page_name = 'Audit.html'
    context = {}
    page = render(request=request, template_name=page_name, context=context)
    return page

@login_required(login_url='login')
def ShowDataInfo(request):
    page_name = "ShowDate.html"
    context = {}
    print(us)
    Values_Unary = models.UserInfor.objects.filter(username=us)
    # Item_Unary = [[_.id, _.ProvinceName, _.TreeSpecies, _.Commit, _.TreeType,
    #                _.City, _.Pos, _.Quantity, _.Diameter, _.Height,
    #                _.dry_biomass, _.total_biomass, _.carbon_storage,
    #                _.total_carbon_storage_all, _.carbon_sinks] for _ in Values_Unary]

    Item_Unary = [_ for _ in Values_Unary]

    context['Item_Unary'] = Item_Unary
    page = render(request=request, template_name=page_name, context=context)
    return page